<?php
class License{
	public $Area;
	public $Role;
	function __construct($area, $role){
		$this->Area = unpack('C*', $area ) ;
		$this->Role = $role;
	}
	function getArea(){
		return implode(array_map("chr",  $this->Area )) ;
	}
}
class DataGroup{
	private $AreaNRole = array(); 
	private $SecretCode;
	function __construct(){
		$this->SecretCode = unpack('C*', UtilHash::generateKey( 32 )  ) ;
	}
	static function swap($bytebuffer){
		{Error::getInstance() ->addError( 1 , "read group len:". $bytebuffer->remaining() );} ;
		$obj = new DataGroup();
		$num_of_license = DataUtil::readInt32( $bytebuffer ) ;
		{Error::getInstance() ->addError( 1 , "num_of_license " . $num_of_license );} ;
		for($i = 0; $i < $num_of_license; $i++){
			$role = DataUtil::readInt8( $bytebuffer ) ;
			$area = implode(array_map("chr",  DataUtil::readBBin( $bytebuffer )  )) ;
			{Error::getInstance() ->addError( 1 , "license" . $role . $area );} ;
			$license = new License($area,$role);
			$obj->AreaNRole[] = $license;
		}
		$obj->SecretCode = DataUtil::readBBin( $bytebuffer ) ;
		return $obj;
	}
	function addRole($area,$role){
		if(is_array($this->AreaNRole)){
			foreach($this->AreaNRole as $license){
				if($license->getArea() == $area){
					$license->Role = $role;
					return;
				}
			}			
		}else{
			$this->AreaNRole = array();
		}
		$newlicense = new License($area,$role);
		$this->AreaNRole[] = $newlicense;
	}
	function getLicense($area){
		if(is_array($this->AreaNRole)){
			foreach($this->AreaNRole as $license){
				if($license->getArea() == $area){
					return $license->Role;
				}
			}
		}
		return (-1) ;
	}
	function getSecretCode(){
		return implode(array_map("chr",  $this->SecretCode )) ;
	}
	function getBinSize(){
		$size = 0;
		$size += 4 ;
		if(is_array($this->AreaNRole)){
			foreach($this->AreaNRole as $license){
				$size += 1 ;
				$size += 1  + count($license->Area);
			}
		}
		$size += 1  + count($this->SecretCode);
		return $size;
	}
	function getBinary(){
		$buf = ByteBuffer::allocate( $this->getBinSize() ) ;
		DataUtil::writeInt32( $buf ,  count($this->AreaNRole) ) ;
		if(is_array($this->AreaNRole)){
			foreach($this->AreaNRole as $license){
				DataUtil::writeInt8( $buf , $license->Role ) ;
				DataUtil::writeBBin( $buf , $license->Area ) ;
			}
		}
		DataUtil::writeBBin( $buf , $this->SecretCode ) ;
		{Error::getInstance() ->addError( 1 , "Write group len:".$this->getBinSize() );} ;
		return  $buf ->_array() ;
	}
}
?>